<template>
	<view class="content">
		<view class="row category">
			<text class="tip">发布到:</text>
			<picker mode="selector" :range="catelist" value="0" range-key="name" @change="changeCategory">
				<view>{{name}}</view>
			</picker>
			<text class="drop"></text>
		</view>
		<view class="row">
			<input class="title" v-model="title" type="text" placeholder="文章标题在此填写">
		</view>
		<view class="row">
			<textarea class="context" v-model="context" placeholder="请输入内容250字以内"></textarea>
		</view>
		<view class="row">
			<view class="imgs">
				<view class="img" v-for="(tempImg,index) in tempImgArr" @click="removeImg(index)">
					<image :src="tempImg.uri" mode="aspectFill"></image>
					<text class="del iconfont icon-delete"></text>
				</view>
				<view class="img" @click="chooseImg" v-show="tempImgArr.length<3">
					<image src="../../static/add.png" mode="widthFix"></image>
				</view>
				<text class="number">{{tempImgArr.length}}/3</text>
			</view>
		</view>
		<view class="row">
			<button class="publish" @click="publish">发布</button>
		</view>
	</view>
</template>

<script>
	import {
		ref,
		toRefs,
		reactive,
		onMounted,
		getCurrentInstance
	} from 'vue';
	import home from '../../apis/home/index.js'
	import post from '../../apis/publish/index.js'
	export default {
		setup() {
			const {
				proxy
			} = getCurrentInstance();
			const state = reactive({
				catelist: [],
				cateid: "",
				name: "请选择",
				tempImgArr: [],
				title: "",
				context: "",
				imageSrc: []
			})

			onMounted(function() {
				home.get_cate_list().then(res => {
					console.log(res.data.data);
					state.catelist = res.data.data;
				})
			})

			const changeCategory = (e) => {
				state.name = state.catelist[e.detail.value].name;
				state.cateid = state.catelist[e.detail.value]._id;
			}

			const chooseImg = () => {
				uni.chooseImage({
					count: 3 - state.tempImgArr.length,
					sizeType: ["compressed"],
					sourceType: ["album"],
					success: (res) => {
						//构造上传图片的数据结构
						let tempFile = res.tempFilePaths.map(i => {
							return {
								name: Math.random(),
								uri: i
							}
						})

						state.tempImgArr = [...tempFile, ...state.tempImgArr];
						console.log(state.tempImgArr);
					}
				})
			}

			const removeImg = (index) => {
				uni.showModal({
					title: "点击确认删除？",
					success(e) {
						if (e.confirm) {
							state.tempImgArr.splice(index, 1);
						}
					}
				})
			}

			const publish = () => {


				//分类验证
				if (state.cateid.trim() == "") {
					uni.showToast({
						title: "请选择一个分类",
						icon: 'error'
					})
					return;
				}
				//标题验证
				if (state.title.trim().length < 6) {
					uni.showToast({
						title: "标题不少于6字",
						icon: 'error'
					})
					return;
				}
				//内容验证
				if (state.context.trim().length <= 20) {
					uni.showToast({
						title: "不要灌水",
						icon: 'error'
					})
					return;
				}

				const token = proxy.$checkLogin();
				if (token) {
					//判断是否选中了图片
					if (state.tempImgArr.length == 0) {
						//没有图片上传，可直接发布文章
						SendArticle();
					} else {
						// 先上传图片,在发布帖子	
						let files = JSON.parse(JSON.stringify(state.tempImgArr));

						//上传提示
						uni.showLoading({
							title: '上传中...'
						})
						uni.uploadFile({
							url: "https://test.galayun.com/smallprogapi/appcirclepost/PostUniImages",
							files: files,
							success: async (res) => {
								//处理数据
								let data = await JSON.parse(res.data);
								state.imageSrc = data.data.Data;

								//发送文章到服务器
								SendArticle();
							}
						})
					}
				} else {
					console.log("未登录");
				}
			}

			//发布文章
			const SendArticle = async () => {
				const {
					uid,
					nickname
				} = uni.getStorageSync("token");
				const data = {
					title: state.title,
					content: state.context,
					cate_id: state.cateid,
					cate_name: state.name,
					author: nickname,
					author_id: uid,
					imageSrc: state.imageSrc
				}
				// console.log(data)
				post.add_article(data).then(res => {
					console.log(res);
					uni.showToast({
						title: "发布成功"
					})
				}).catch(err => {});
				// let a={"title":"发布了多少次？","content":"你们可能不能体会到做这个功能由多么艰辛，如果能够提供开发的文档那么就不需要翻书找请求的参数与接口了","cate_id":"60e83b96827eca0001ba827c","cate_name":"心灵鸡汤","author":"夺别亚斯","author_id":"62de1277b717e800015b1efd","imageSrc":["http://images.galayun.com/Storage/VueStudent/20221129123229284759.png"]} ;

				// const result = await post.add_article(a);
				// console.log(result);
			}


			return {
				...toRefs(state),
				onMounted,
				changeCategory,
				chooseImg,
				removeImg,
				publish,
				SendArticle
			}

		}
	}
</script>

<style lang="scss" scoped>
	@import url("https://at.alicdn.com/t/c/font_3630446_w2q4khqm4ro.css");

	.row {
		background-color: #ffffff;
		font-size: 48rpx;
		margin: 30rpx 0rpx;
		padding: 18rpx;

		.context {
			width: 100%;
		}

		.imgs {
			width: 100%;
			position: relative;

			.img {
				display: inline-block;
				width: 100rpx;
				height: 100rpx;
				margin-left: 20rpx;
				position: relative;

				text {
					position: absolute;
					top: 38rpx;
					left: 38rpx;
					font-size: 24rpx;
					font-weight: 700;
					color: #ffffff;
				}

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.publish {
			background-color: #4aaf45;
			color: #ffffff;
		}
	}

	.category {
		display: flex;
		font-size: 32rpx;

		text {
			flex: 1;
			font-weight: 800;
		}

		picker {
			flex: 4;
		}

		.drop {
			background-image: url('../../static/down.png');
			background-repeat: no-repeat;
			background-position-x: 60rpx;
			background-position-y: 0rpx;
			background-size: 40rpx;
		}
	}

	.number {
		font-size: 24rpx;
		position: absolute;
		right: 30rpx;
		bottom: 10rpx;
		color: #cccccc;
	}
</style>
